package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.02.21
 * @since 1.0
 */
@Service
public class DtsAdminServiceImpl implements DtsAdminService {

    @Autowired
    DtsAdminMapper adminMapper;

    @Override
    public IPage queryPage(Integer page, Integer limit, String username, String sort, String order) {


        IPage<DtsAdmin> ipage = new Page<>(page,limit);
        QueryWrapper<DtsAdmin> wapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(username)){
            wapper.like("username",username);
        }
        //排序操作
        if(!StringUtils.isEmpty(sort)  && !StringUtils.isEmpty(order)){
            //降序排序
            if(order.equalsIgnoreCase("desc")){
                wapper.orderByDesc(sort);
                //升序排序
            }else{
                wapper.orderByAsc(sort);
            }
        }
        //没有逻辑删除
        wapper.eq("deleted",false);

        ipage= adminMapper.selectPage(ipage,wapper);

        return ipage;
    }

    @Override
    public DtsAdmin insert(DtsAdmin admin) {

        //对密码进行加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(password);

        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setDeleted(false);

        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public DtsAdmin update(DtsAdmin admin) {

        //从数据库查询admin
        DtsAdmin adminDb = adminMapper.selectById(admin.getId());
        //如果数据库的密码和前端传回来的密码不一致，说明前端传回来的是明文，需要加密
        if(admin.getPassword() == null || !admin.getPassword().equals(adminDb.getPassword())){
           BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode(admin.getPassword());
            admin.setPassword(password);
        }
        admin.setUpdateTime(new Date());

        adminMapper.updateById(admin);

        return admin;
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }
}
